package com.cci.kangdao.service.impl;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.SSRepairTDao;
import com.cci.kangdao.dao.StationAuditDao;
import com.cci.kangdao.service.StationAuditService;
import com.cci.kangdao.utilTool.ParameterTool;

@Service("StationAuditService")
public class StationAuditServiceImpl implements StationAuditService{
	
	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Autowired
	private StationAuditDao stationAuditDao;
	@Autowired
	private SSRepairTDao sSRepairTDao;

	//根据授权id，层级，岗位获取服务站审核表中的数据
	@Transactional
	@Override
	public ModelAndView getStationAuditBySSRIDLevelPosition(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			//拿到传的ServiceStationID和CompanyID，获取SSRepairT表中唯一的一条数据
			List<Map<String, Object>> SSRepairTList = sSRepairTDao.getSSRepairTByServiceStationIDCompanyID(map);
			JSONObject obj = new JSONObject();
			//拿到传的企业id,服务站id和故障地点距离，通过企业id,服务站id和故障地点距离调用CRM接口获取到用户层级和岗位
			CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().getApprovalLevel(String.valueOf(map.get("CompanyID")), String.valueOf(map.get("ServiceStationID")),String.valueOf(map.get("distance")));
			if(SSRepairTList != null) {
				map.put("SSRID", SSRepairTList.get(0).get("id"));
			}
			map.put("Level", cRMResponeEntity.getData().get("approvalLevel"));
			map.put("Position", cRMResponeEntity.getData().get("positionNo"));
			//根据授权id，层级，岗位获取服务站审核表中的数据
			List<Map<String, Object>> stationAuditList = stationAuditDao.getStationAuditBySSRIDLevelPosition(map);
			obj.put("status", 0);
			obj.put("msg", "查询成功");
			obj.put("data", new JSONObject().put("stationAuditList", stationAuditList));
			ParameterTool.writeResponse(response, obj.toString());	
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);	
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}
	

}
